<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h3>聊天室</h3>
        <h4>房间号: {{ room_id }}</h4>
        <textarea id="chat-log" cols="100" rows="20"></textarea><br/>
        <input id="chat-message-input" type="text" size="100"/><br/>
        <input id="chat-message-submit" type="button" value="Send"/>
    </body>

    <script>
        var roomName = {{ room_id }};

        var chatSocket = new WebSocket('ws://' + window.location.host + '/ws/room/' + roomName + '/');

        chatSocket.onmessage = function (e) {
            var data = JSON.parse(e.data);
            document.querySelector('#chat-log').value += (JSON.stringify(data).slice(1,-1) + '\n');
        };

        chatSocket.onclose = function (e) {
            console.error('Chat socket closed unexpectedly');
        };

        document.querySelector('#chat-message-input').focus();
        document.querySelector('#chat-message-input').onkeyup = function (e) {
            if (e.keyCode === 13) {  // enter, return
                document.querySelector('#chat-message-submit').click();
            }
        };

        document.querySelector('#chat-message-submit').onclick = function (e) {
            var messageInputDom = document.querySelector('#chat-message-input');
            var message = messageInputDom.value;
            chatSocket.send(JSON.stringify(message));

            messageInputDom.value = '';
        };
    </script>
</html>